<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="核销码" prop="verificationCode">
        <el-input v-model="queryParams.verificationCode" placeholder="请输入核销码" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="店铺名称" prop="mid">
        <el-select v-model="queryParams.mid" placeholder="请选择店铺" clearable>
          <el-option
            v-for="merchant in merchants"
            :key="merchant.id"
            :label="merchant.name"
            :value="merchant.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="用户名称" prop="userId">
        <el-select v-model="queryParams.userId" placeholder="请选择用户" clearable>
          <el-option
            v-for="user in users"
            :key="user.id"
            :label="user.userName"
            :value="user.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="服务类别" prop="serviceTypeId">
        <el-select v-model="queryParams.serviceTypeId" placeholder="请选择服务类别id" clearable>
          <el-option
            v-for="serviceType in serviceTypes"
            :key="serviceType.id"
            :label="serviceType.name"
            :value="serviceType.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="下单时间" prop="orderTime">
        <el-date-picker clearable v-model="queryParams.orderTime" type="date" value-format="YYYY-MM-DD"
          placeholder="请选择下单时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="预约时间" prop="reservationTime">
        <el-date-picker clearable v-model="queryParams.reservationTime" type="date" value-format="YYYY-MM-DD"
          placeholder="请选择预约时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="订单车辆id号" prop="carId">
        <el-select v-model="queryParams.carId" placeholder="请选择订单车辆id号" clearable>
          <el-option v-for="dict in order_status" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="优惠券" prop="couponId">
        <el-select v-model="queryParams.couponId" placeholder="请选择优惠券id" clearable>
          <el-option
            v-for="coupon in coupons"
            :key="coupon.id"
            :label="coupon.name"
            :value="coupon.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="实付价格" prop="price">
        <el-input v-model="queryParams.price" placeholder="请输入实付价格" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="支付时间" prop="payTime">
        <el-date-picker clearable v-model="queryParams.payTime" type="date" value-format="YYYY-MM-DD"
          placeholder="请选择支付时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="订单状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择订单状态" clearable>
          <el-option v-for="dict in order_status" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="是否评价" prop="evaluate">
        <el-select v-model="queryParams.evaluate" placeholder="请选择是否评价" clearable>
          <el-option v-for="dict in evaluate_status" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['orders:orders:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['orders:orders:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['orders:orders:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['orders:orders:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="ordersList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="订单编号" align="center" prop="id" />
      <el-table-column label="核销码" align="center" prop="verificationCode" />
      <el-table-column label="核销码图片" align="center" prop="verificationImg" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.verificationImg" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="服务详情" align="center" prop="serviceId">
        <template #default="scope">
          <el-button type="primary" @click="lookServices(scope.row)" plain>查看</el-button>
        </template>
      </el-table-column>
      <el-table-column label="店铺名称" align="center" prop="mName">
        <template #default="scope">
          {{scope.row.mName}}
        </template>
      </el-table-column>
      <el-table-column label="用户名称" align="center" prop="userName">
        <template #default="scope">
          {{ scope.row.userName }}
        </template>
      </el-table-column>
      <el-table-column label="服务类别" align="center" prop="serviceType">
        <template #default="scope">
          {{ scope.row.serviceType }}
        </template>
      </el-table-column>
      <el-table-column label="下单时间" align="center" prop="orderTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.orderTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="预约时间" align="center" prop="reservationTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.reservationTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="订单车辆id号" align="center" prop="carId">
        <template #default="scope">
          <dict-tag :options="order_status" :value="scope.row.carId" />
        </template>
      </el-table-column>
      <el-table-column label="优惠券id" align="center" prop="CouponName">
        <template #default="scope">
          {{ scope.row.CouponName }}
        </template>
      </el-table-column>
      <el-table-column label="实付价格" align="center" prop="price" />
      <el-table-column label="支付时间" align="center" prop="payTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.payTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="订单状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="order_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="是否评价" align="center" prop="evaluate">
        <template #default="scope">
          <dict-tag :options="evaluate_status" :value="scope.row.evaluate" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['orders:orders:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['orders:orders:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>


    <el-dialog v-model="dialogVisible1" title="Tips" width="500" :before-close="handleClose">

      <el-table :data="services">
        <el-table-column property="name" label="服务名称" width="150" />
      </el-table>
      <!-- <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogVisible = false">Cancel</el-button>
            <el-button type="primary" @click="dialogVisible = false">
              Confirm
            </el-button>
          </div>
        </template> -->
    </el-dialog>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改订单信息对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="ordersRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="核销码" prop="verificationCode">
          <el-input v-model="form.verificationCode" placeholder="请输入核销码" />
        </el-form-item>
        <el-form-item label="核销码图片" prop="verificationImg">
          <image-upload v-model="form.verificationImg" />
        </el-form-item>
        <el-form-item label="服务编号id" prop="serviceId">
          <el-select v-model="form.serviceId" placeholder="请选择服务编号id">
            <el-option v-for="dict in order_status" :key="dict.value" :label="dict.label"
              :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="店铺id" prop="mid">
          <el-select v-model="form.mid" placeholder="请选择店铺id">
            <el-option v-for="dict in order_status" :key="dict.value" :label="dict.label"
              :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="服务类别id" prop="serviceTypeId">
          <el-select v-model="form.serviceTypeId" placeholder="请选择服务类别id">
            <el-option v-for="dict in order_status" :key="dict.value" :label="dict.label"
              :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="下单时间" prop="orderTime">
          <el-date-picker clearable v-model="form.orderTime" type="date" value-format="YYYY-MM-DD"
            placeholder="请选择下单时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="预约时间" prop="reservationTime">
          <el-date-picker clearable v-model="form.reservationTime" type="date" value-format="YYYY-MM-DD"
            placeholder="请选择预约时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="订单车辆id号" prop="carId">
          <el-select v-model="form.carId" placeholder="请选择订单车辆id号">
            <el-option v-for="dict in order_status" :key="dict.value" :label="dict.label"
              :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="优惠券id" prop="couponId">
          <el-select v-model="form.couponId" placeholder="请选择优惠券id">
            <el-option v-for="dict in order_status" :key="dict.value" :label="dict.label"
              :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="实付价格" prop="price">
          <el-input v-model="form.price" placeholder="请输入实付价格" />
        </el-form-item>
        <el-form-item label="支付时间" prop="payTime">
          <el-date-picker clearable v-model="form.payTime" type="date" value-format="YYYY-MM-DD" placeholder="请选择支付时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="订单状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择订单状态">
            <el-option v-for="dict in order_status" :key="dict.value" :label="dict.label"
              :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="删除状态" prop="deleted">
          <el-select v-model="form.deleted" placeholder="请选择删除状态">
            <el-option v-for="dict in sys_user_sex" :key="dict.value" :label="dict.label"
              :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否评价" prop="evaluate">
          <el-select v-model="form.evaluate" placeholder="请选择是否评价">
            <el-option v-for="dict in evaluate_status" :key="dict.value" :label="dict.label"
              :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="保留字段1" prop="reserved1">
          <el-input v-model="form.reserved1" placeholder="请输入保留字段1" />
        </el-form-item>
        <el-form-item label="保留字段2" prop="reserved2">
          <el-input v-model="form.reserved2" placeholder="请输入保留字段2" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Orders">
import { listOrders, getOrders, delOrders, addOrders, updateOrders, serviceListwwc } from "@/api/orders/orders"
import { listwwc } from "../../../api/xyq/details"
import { getMerchant,listMerchant } from "../../../api/wx/merchant"
import { getType,listType } from "../../../api/xyq/type"
import { getCoupon,listCoupon } from "../../../api/coupon/coupon"
import { getUser,listUser } from "../../../api/user/user"
import { ref } from "vue"

const { proxy } = getCurrentInstance()
const { order_status, sys_user_sex, evaluate_status } = proxy.useDict('order_status', 'sys_user_sex', 'evaluate_status')

const ordersList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    verificationCode: null,
    serviceId: null,
    mid: null,
    serviceTypeId: null,
    orderTime: null,
    reservationTime: null,
    carId: null,
    couponId: null,
    price: null,
    payTime: null,
    status: null,
    evaluate: null,
    userId: null
  },
  rules: {
  }
})

const { queryParams, form, rules } = toRefs(data)
const query = ref({
  orderId: 0,
  ids: []
})
const services = ref([])

/** 查询订单信息列表 */
async function getList() {
  loading.value = true;
  try {
    const response = await listOrders(queryParams.value);
    ordersList.value = response.rows;
    console.log(ordersList.value);
    total.value = response.total;

    // 使用 for...of 循环确保顺序执行
    for (const order of ordersList.value) {
      query.value.orderId = order.id;
      const res = await serviceListwwc(query.value); // 等待每个请求完成
      console.log(res.data);
      query.value.ids = res.data;
      services.value = await listwwc(query.value);
      console.log(services.value);

      const response1 = await getMerchant(order.mid);
      console.log(response1.data);
      order.mName = response1.data.name
      console.log(order.mName);

      const response2 = await getType(order.serviceTypeId);
      order.serviceType = response2.data.name

      const response3 = await getCoupon(order.couponId);
      order.CouponName = response3.data.name

      const response4 = await getUser(order.userId);
      order.userName = response4.data.userName

    }



  } catch (error) {
    console.error('请求出错:', error);
  } finally {
    loading.value = false;
  }
}
const dialogVisible1 = ref(false)

const lookServices = async (e) => {
  dialogVisible1.value = true;
  services.value = []

  query.value.orderId = e.id;
  const res = await serviceListwwc(query.value); // 等待每个请求完成
  console.log(res.data);
  query.value.ids = res.data;
  const res2 = await listwwc(query.value);
  services.value = res2.data;
  console.log(services.value);

}
// -------------------------------------------------------------
const merchants = ref([])
const serviceTypes = ref([])
const coupons = ref([])
const users = ref([])

function getMerchants(){
  listMerchant(null).then(res=>{
    merchants.value = res.rows;
  })
}

function getServiceTypes(){
  listType(null).then(res=>{
    serviceTypes.value = res.rows;
  })
}

function getCoupons(){
  listCoupon(null).then(res=>{
    coupons.value = res.rows;
  })
}

function getUsers(){
  listUser(null).then(res=>{
    users.value = res.rows;
  })
}

getMerchants()
getServiceTypes()
getCoupons()
getUsers()

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    verificationCode: null,
    verificationImg: null,
    serviceId: null,
    mid: null,
    serviceTypeId: null,
    orderTime: null,
    reservationTime: null,
    carId: null,
    couponId: null,
    price: null,
    payTime: null,
    status: null,
    deleted: null,
    evaluate: null,
    reserved1: null,
    reserved2: null
  }
  proxy.resetForm("ordersRef")
}



/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加订单信息"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getOrders(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改订单信息"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["ordersRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateOrders(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addOrders(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除订单信息编号为"' + _ids + '"的数据项？').then(function () {
    return delOrders(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => { })
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('orders/orders/export', {
    ...queryParams.value
  }, `orders_${new Date().getTime()}.xlsx`)
}

getList()
</script>
